import { open } from "@tauri-apps/plugin-dialog";
import { exists, readFile } from "@tauri-apps/plugin-fs";
import { error } from "@tauri-apps/plugin-log";

export function openTextFile(uri?: string): Promise<string> {
    return new Promise(async (resolve, reject) => {
        if (uri == undefined) {
            const tmpPath = await open();
            if (tmpPath == null) {
                reject("User abort");
                return;
            } else {
                uri = tmpPath;
            }
        }
        const u8 = await readFile(uri);
        const d = new TextDecoder('gb18030');
        resolve(d.decode(u8));
    })
}

export async function readUriToText(uri: string) {
    let uriExists = false;
    try {
        uriExists = await exists(uri);
    } catch (e) {
        await error(`Failed to validate uri existence, ${e}`);
        return "";
    }
    if (!uriExists) {
        console.error('file does not exists', uri);
        return "";
    }
    let raw = "";
    try {
        raw = await openTextFile(uri);
    } catch (e) {
        await error(`Failed to read raw file: ${e}`);
        return "";
    }
    console.log('read complete', raw);
    return raw;
}

/**
 * 读取文件为文本，按行分割为数组，并过滤掉skipMark后的内容
 * @param uri 文件路径
 * @param skipMark
 */
export async function readUriToTextAndExplode(uri: string, skipMark?: string) {
    const content = await readUriToText(uri);
    const lines = content.split("\n");
    console.log('step1 lines', uri, lines);
    if (skipMark == undefined) return lines;
    const result: string[] = [];
    for (let i = 0; i < lines.length; i++) {
        let line = lines[i];
        if (line.length == 0) continue;// 如果为空行，则跳过
        line = line.trim();//处理前后空格
        if (line.startsWith(';')) continue;// 如果开头就是注释，则直接跳过本行
        if (line.lastIndexOf(';') != -1) {// 如果一行中既存在注释也存在非注释，则去掉注释部分，剩余部分继续处理
            line = line.substring(0, line.lastIndexOf(';') + 1);
        }
        while (line.lastIndexOf('\\') != -1) {
            line = line.replace('\\', '/');
        }
        result.push(line);
    }
    return result;
}